package com.lh.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lh.entity.table.*;
import com.lh.mapper.*;
import com.lh.service.ApprovalRecordService;
import com.lh.service.RectificationInfoApprovalService;
import com.lh.service.RectificationInfoService;
import com.lh.service.TicketProblemInfoApprovalService;
import com.lh.utils.Answer;
import com.lh.utils.RectificationClassifier;
import com.lh.utils.RectificationWithDepartmentClassifier;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.mapping.IdGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.support.collections.DefaultRedisList;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.lh.utils.DateAddDemo.calculateFutureDate;

@Service
public class RectificationInfoApprovalServiceImpl implements RectificationInfoApprovalService {
    @Resource
    private RectificationInfoApprovalMapper rectificationInfoApprovalMapper;

    @Autowired
    private ResponsiblePersonsServiceImpl responsiblePersonsService;

    @Resource
    private RectificationInfoMapper rectificationInfoMapper;

    @Resource
    private DeadlineNodeApprovalMapper  deadlineNodeApprovalMapper;

    @Resource
    private DeadlineNodeMapper deadlineNodeMapper;

    @Resource
    private TicketProblemInfoApprovalMapper ticketProblemInfoApprovalMapper;

    @Resource
    private TicketProblemInfoMapper ticketProblemInfoMapper;

    @Resource
    private TaskInfoMapper taskInfoMapper;

    @Resource
    private Task2InfoMapper task2InfoMapper;

    @Resource
    private Task1InfoMapper task1InfoMapper;

    @Resource
    private ApprovalRecordService approvalRecordService;

    @Autowired
    private CompanyDataMapper companyDataMapper;
    @Autowired
    private EnterpriseDataMapper enterpriseDataMapper;

    @Resource
    private DeadlineRectificationPeriodMapper deadlineRectificationPeriodMapper;

    @Override
    public Answer<Object> commitApproval(RectificationInfoApproval rectificationInfoApproval) {
        Integer id = rectificationInfoApproval.getRectificationId();
        if (id==null) {
            return Answer.error("项目id不能为空");
        }
        RectificationInfoApproval rectificationInfoApproval1 = rectificationInfoApprovalMapper.selectOne(new LambdaQueryWrapper<RectificationInfoApproval>()
                .eq(RectificationInfoApproval::getRectificationId,id).eq(RectificationInfoApproval::getApprovalState,0)
                .ne(RectificationInfoApproval::getState,"已关闭").ne(RectificationInfoApproval::getState,"已销号").ne(RectificationInfoApproval::getState,"已退出"));

        if (rectificationInfoApproval1!=null){
            rectificationInfoApproval1.setApprovalState("0");
            rectificationInfoApproval1.setState(rectificationInfoApproval.getState()!=null? rectificationInfoApproval.getState() : "待审核");
            rectificationInfoApproval1.setApprovalUrl(rectificationInfoApproval.getApprovalUrl());
            rectificationInfoApproval1.setApplyReason(rectificationInfoApproval.getApplyReason());
            rectificationInfoApproval1.setApprovalRemake(rectificationInfoApproval.getApprovalRemake());
            if(rectificationInfoApproval.getState() !=null && rectificationInfoApproval.getState().equals("进行中")){
                rectificationInfoApproval.setApprovalState("1");
            }
            rectificationInfoApprovalMapper.updateById(rectificationInfoApproval1);
            if (rectificationInfoApproval.getState() !=null && rectificationInfoApproval.getState().contains("不通过")){
                return Answer.ok("审核成功");
            }
        }else {
            rectificationInfoApproval.setId(null);
            rectificationInfoApprovalMapper.insert(rectificationInfoApproval);
        }
        List<DeadlineNodeApproval> deadlineNodeApprovalList1 = deadlineNodeApprovalMapper.selectList(new LambdaQueryWrapper<DeadlineNodeApproval>().eq(DeadlineNodeApproval::getRectificationId, rectificationInfoApproval.getId()));
        if (deadlineNodeApprovalList1==null||deadlineNodeApprovalList1.isEmpty()) {
            List<DeadlineNode> deadlineNodeList = deadlineNodeMapper.selectList(new LambdaQueryWrapper<DeadlineNode>().eq(DeadlineNode::getRectificationId, rectificationInfoApproval.getId()));
            if (deadlineNodeList != null && !deadlineNodeList.isEmpty()) {
                List<DeadlineNodeApproval> deadlineNodeApprovalList = new ArrayList<>();
                // 遍历列表，逐个复制对象属性
                for (DeadlineNode node : deadlineNodeList) {
                    DeadlineNodeApproval approval = new DeadlineNodeApproval();
                    // 复制单个对象的属性
                    BeanUtils.copyProperties(node, approval);
                    deadlineNodeApprovalList.add(approval);
                }
                deadlineNodeApprovalMapper.batchInsertByAnnotation(deadlineNodeApprovalList);
            }
        }
        List<TicketProblemInfoApproval> ticketProblemInfoApprovalList1 = ticketProblemInfoApprovalMapper.selectList(new LambdaQueryWrapper<TicketProblemInfoApproval>().eq(TicketProblemInfoApproval::getRectificationId, rectificationInfoApproval.getId()));
        if (ticketProblemInfoApprovalList1==null||ticketProblemInfoApprovalList1.isEmpty()) {
            List<TicketProblemInfo> ticketProblemInfos = ticketProblemInfoMapper.selectList(new LambdaQueryWrapper<TicketProblemInfo>().eq(TicketProblemInfo::getRectificationId, rectificationInfoApproval.getId()));
            if (ticketProblemInfos != null && !ticketProblemInfos.isEmpty()) {
                List<TicketProblemInfoApproval> ticketProblemInfoApprovalList = new ArrayList<>();
                // 遍历列表，逐个复制对象属性
                for (TicketProblemInfo ticketProblemInfo : ticketProblemInfos) {
                    TicketProblemInfoApproval ticketProblemInfoApproval = new TicketProblemInfoApproval();
                    // 复制单个对象的属性
                    BeanUtils.copyProperties(ticketProblemInfo, ticketProblemInfoApproval);
                    ticketProblemInfoApprovalList.add(ticketProblemInfoApproval);
                }
                ticketProblemInfoApprovalMapper.batchInsertByAnnotation(ticketProblemInfoApprovalList);
            }
        }
        return Answer.ok("提交审批成功");
    }

    /**
     * 修改项目,确认按钮
     * 生成项目的ticket表
     * @param rectificationInfoApproval
     * @return
     */
    @Override
    public Answer<Object> approval(RectificationInfoApproval rectificationInfoApproval) {
        Integer id = rectificationInfoApproval.getRectificationId();
        if (id==null) {
            return Answer.error("项目id不能为空");
        }
        RectificationInfoApproval rectificationInfoApproval1 = rectificationInfoApprovalMapper.selectOne(new LambdaQueryWrapper<RectificationInfoApproval>()
                .eq(RectificationInfoApproval::getRectificationId,id).eq(RectificationInfoApproval::getApprovalState,0)
                .ne(RectificationInfoApproval::getState,"已关闭").ne(RectificationInfoApproval::getState,"已销号").ne(RectificationInfoApproval::getState,"已退出"));
        if (rectificationInfoApproval1!=null) {
            return Answer.ok("已经存在待修改的本项目");
        }else {
            RectificationInfo rectificationInfo = rectificationInfoMapper.selectById(id);
            RectificationInfoApproval rectificationInfoApproval2 = new RectificationInfoApproval();
            BeanUtils.copyProperties(rectificationInfo,rectificationInfoApproval2);
            rectificationInfoApproval2.setApplyReason(rectificationInfoApproval.getApplyReason());
            rectificationInfoApproval2.setApprovalUrl(rectificationInfoApproval.getApprovalUrl());
            rectificationInfoApproval2.setState("进行中");
            rectificationInfoApproval2.setId(null);
            rectificationInfoApproval2.setRectificationId(rectificationInfo.getId());
            rectificationInfoApproval2.setApprovalState("0");
            rectificationInfoApprovalMapper.insert(rectificationInfoApproval2);
            deadlineNodeApprovalMapper.delete(new LambdaQueryWrapper<DeadlineNodeApproval>().eq(DeadlineNodeApproval::getRectificationId, rectificationInfoApproval.getRectificationId()));
            ticketProblemInfoApprovalMapper.delete(new LambdaQueryWrapper<TicketProblemInfoApproval>().eq(TicketProblemInfoApproval::getRectificationId, rectificationInfoApproval.getRectificationId()));
            List<TicketProblemInfo> ticketProblemInfos = ticketProblemInfoMapper.selectList(
                    new LambdaQueryWrapper<TicketProblemInfo>().eq(
                            TicketProblemInfo::getRectificationId,
                            rectificationInfoApproval.getRectificationId()));
            if (ticketProblemInfos != null && !ticketProblemInfos.isEmpty()) {
                List<TicketProblemInfoApproval> ticketProblemInfoApprovalList = new ArrayList<>();
                // 遍历列表，逐个复制对象属性
                for (TicketProblemInfo ticketProblemInfo : ticketProblemInfos) {
                    TicketProblemInfoApproval ticketProblemInfoApproval = new TicketProblemInfoApproval();
                    // 复制单个对象的属性
                    BeanUtils.copyProperties(ticketProblemInfo, ticketProblemInfoApproval);
                    ticketProblemInfoApprovalList.add(ticketProblemInfoApproval);
                    ticketProblemInfoApprovalMapper.insert(ticketProblemInfoApproval);
                    Integer ticketId = ticketProblemInfoApproval.getId();
                    List<DeadlineNode> deadlineNodeList =
                            deadlineNodeMapper.selectList(new LambdaQueryWrapper<DeadlineNode>().
                                    eq(DeadlineNode::getMainId,
                                            ticketProblemInfo.getId()));
                    if (deadlineNodeList != null && !deadlineNodeList.isEmpty()) {
                        List<DeadlineNodeApproval> deadlineNodeApprovalList = new ArrayList<>();
                        // 遍历列表，逐个复制对象属性
                        for (DeadlineNode node : deadlineNodeList) {
                            DeadlineNodeApproval approval = new DeadlineNodeApproval();
                            // 复制单个对象的属性
                            BeanUtils.copyProperties(node, approval);
                            approval.setMainId(ticketId);
                            deadlineNodeApprovalList.add(approval);
                        }
                        deadlineNodeApprovalMapper.batchInsertByAnnotation(deadlineNodeApprovalList);
                    }
                }
            }else{

                List<DeadlineNode> deadlineNodeList = deadlineNodeMapper.selectList(new LambdaQueryWrapper<DeadlineNode>().eq(DeadlineNode::getRectificationId, rectificationInfoApproval.getRectificationId()));
                if (deadlineNodeList != null && !deadlineNodeList.isEmpty()) {
                    List<DeadlineNodeApproval> deadlineNodeApprovalList = new ArrayList<>();
                    // 遍历列表，逐个复制对象属性
                    for (DeadlineNode node : deadlineNodeList) {
                        DeadlineNodeApproval approval = new DeadlineNodeApproval();
                        // 复制单个对象的属性
                        BeanUtils.copyProperties(node, approval);
                        deadlineNodeApprovalList.add(approval);
                    }
                    deadlineNodeApprovalMapper.batchInsertByAnnotation(deadlineNodeApprovalList);
                }

            }
        }
        return Answer.ok("提交成功");
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Answer<Object> passApproval(JSONObject reqJson) {
        Integer id = reqJson.getInteger("id");

        RectificationInfoApproval rectificationInfoApproval = rectificationInfoApprovalMapper.selectById(id);
        if (rectificationInfoApproval!=null) {
            //查询审批中的修改数据
            List<DeadlineNodeApproval> deadlineNodeApprovalList = deadlineNodeApprovalMapper.selectList(new LambdaQueryWrapper<DeadlineNodeApproval>()
                    .eq(DeadlineNodeApproval::getRectificationId, rectificationInfoApproval.getRectificationId()).orderByAsc(DeadlineNodeApproval::getSort));

            List<TicketProblemInfoApproval> ticketProblemInfoApprovalList= ticketProblemInfoApprovalMapper.selectList(new LambdaQueryWrapper<TicketProblemInfoApproval>()
                    .eq(TicketProblemInfoApproval::getRectificationId, rectificationInfoApproval.getRectificationId()));
            if (ticketProblemInfoApprovalList==null||ticketProblemInfoApprovalList.isEmpty()) {
                if (deadlineNodeApprovalList != null && !deadlineNodeApprovalList.isEmpty()) {
//                deadlineNodeMapper.batchInsert(deadlineNodeList);
                    // 提取所有新数据的名称用于批量查询和比对
                    List<String> newNodeNames = deadlineNodeApprovalList.stream()
                            .map(DeadlineNodeApproval::getName)
                            .collect(Collectors.toList());

                    // 批量查询所有已有节点，构建名称到节点的映射
                    List<DeadlineNode> allExistingNodes = deadlineNodeMapper.selectList(
                            new LambdaQueryWrapper<DeadlineNode>().eq(DeadlineNode::getRectificationId, rectificationInfoApproval.getRectificationId()));

                    Map<String, DeadlineNode> existingNodesMap = allExistingNodes.stream()
                            .collect(Collectors.toMap(DeadlineNode::getName, node -> node));

                    List<DeadlineNode> toInsert = new ArrayList<>();
                    List<DeadlineNode> toUpdate = new ArrayList<>();

                    for (DeadlineNodeApproval approval : deadlineNodeApprovalList) {
                        DeadlineNode existingNode = existingNodesMap.get(approval.getName());
                        DeadlineNode node = new DeadlineNode();
                        BeanUtils.copyProperties(approval, node);

                        if (existingNode != null) {
                            // 存在则更新
                            node.setId(existingNode.getId());
                            toUpdate.add(node);
                        } else {
                            // 不存在则新增
                            toInsert.add(node);
                        }
                    }

                    // 执行批量新增
                    if (!toInsert.isEmpty()) {
                        deadlineNodeMapper.batchInsert(toInsert);
                    }

                    // 执行批量更新
                    if (!toUpdate.isEmpty()) {
                        deadlineNodeMapper.batchUpdate(toUpdate); // 假设存在批量更新方法
                    }

                    // 找出需要删除的节点（存在于数据库但不在新数据中的节点）
                    List<Integer> toDeleteIds = allExistingNodes.stream()
                            .filter(node -> !newNodeNames.contains(node.getName()))
                            .map(DeadlineNode::getId)
                            .collect(Collectors.toList());
                    // 执行批量删除
                    if (!toDeleteIds.isEmpty()) {
                        deadlineNodeMapper.batchDelete(toDeleteIds); // 假设存在批量删除方法
                    }
                } else {
                    // 如果新数据为空，则删除所有原有节点
                    deadlineNodeMapper.delete(new LambdaQueryWrapper<DeadlineNode>().eq(DeadlineNode::getRectificationId, rectificationInfoApproval.getRectificationId()));
                }
            }else {
                // 1. 查询数据库中已存在的Ticket记录（按整改ID筛选）
                List<TicketProblemInfo> existingInfos = ticketProblemInfoMapper.selectList(
                        new LambdaQueryWrapper<TicketProblemInfo>()
                                .eq(TicketProblemInfo::getRectificationId, rectificationInfoApproval.getRectificationId())
                );
                // 2. 构建：数据库已有部门 → Ticket的映射（处理部门null值，统一用DEFAULT_NULL_KEY）
                Map<String, TicketProblemInfo> existingDeptMap = existingInfos.stream()
                        .collect(Collectors.toMap(
                                info -> Optional.ofNullable(info.getProcessHandlerDepartment()).orElse("DEFAULT_NULL_KEY"),
                                info -> info,
                                (existing, replacement) -> existing, // 重复部门保留旧数据
                                HashMap::new
                        ));
                // 3. 提取本次提交的所有部门（从ticketProblemInfoApprovalList中获取，处理null值）
                Set<String> submittedDeptSet = new HashSet<>();
                for (TicketProblemInfoApproval approval : ticketProblemInfoApprovalList) {
                    String deptKey = Optional.ofNullable(approval.getProcessHandlerDepartment())
                            .orElse("DEFAULT_NULL_KEY");
                    submittedDeptSet.add(deptKey); // Set自动去重，确保部门唯一
                }
                // 4. 新增逻辑：删除“数据库有但本次提交没有”的部门及关联节点
                if (!existingDeptMap.isEmpty() && !submittedDeptSet.isEmpty()) {
                    // 4.1 找出待删除的部门Key（数据库存在，本次提交不存在）
                    List<String> deptsToDelete = existingDeptMap.keySet().stream()
                            .filter(deptKey -> !submittedDeptSet.contains(deptKey))
                            .collect(Collectors.toList());

                    if (!deptsToDelete.isEmpty()) {
                        // 4.2 提取待删除Ticket的主键ID列表
                        List<Integer> ticketIdsToDelete = deptsToDelete.stream()
                                .map(existingDeptMap::get) // 通过部门Key获取对应的Ticket
                                .map(TicketProblemInfo::getId) // 提取Ticket的主键ID
                                .collect(Collectors.toList());

                        // 4.3 批量删除多余的Ticket
                        ticketProblemInfoMapper.deleteBatchIds(ticketIdsToDelete);

                        // 4.4 批量删除多余Ticket关联的DeadlineNode
                        deadlineNodeMapper.delete(
                                new LambdaQueryWrapper<DeadlineNode>()
                                        .in(DeadlineNode::getMainId, ticketIdsToDelete)
                        );
                    }
                }
                // 5. 保留原有核心逻辑：新增Ticket（本次提交有但数据库没有的部门）+ 同步节点
                List<DeadlineNodeApproval> nodeApprovalList = new ArrayList<>();
                for (TicketProblemInfoApproval approval : ticketProblemInfoApprovalList) {
                    // 统一处理部门null值，与数据库映射逻辑一致
                    String deptKey = Optional.ofNullable(approval.getProcessHandlerDepartment())
                            .orElse("DEFAULT_NULL_KEY");

                    // 5.1 新增：数据库没有该部门的Ticket，则插入新Ticket
                    if (!existingDeptMap.containsKey(deptKey)) {
                        TicketProblemInfo newInfo = new TicketProblemInfo();
                        BeanUtils.copyProperties(approval, newInfo);
                        newInfo.setRectificationId(rectificationInfoApproval.getRectificationId()); // 关联整改ID
                        ticketProblemInfoMapper.insert(newInfo);
                    }

                    // 5.2 同步节点：查询旧节点 → 收集旧节点 → 删除旧节点（原有逻辑）
                    List<DeadlineNodeApproval> deadlineNodeApprovals = deadlineNodeApprovalMapper.selectList(
                            new LambdaQueryWrapper<DeadlineNodeApproval>()
                                    .eq(DeadlineNodeApproval::getMainId, approval.getId())
                                    .orderByAsc(DeadlineNodeApproval::getSort)
                    );
                    nodeApprovalList.addAll(deadlineNodeApprovals); // 收集旧节点，用于后续批量插入
                    deadlineNodeMapper.delete( // 删除旧节点，避免重复
                            new LambdaQueryWrapper<DeadlineNode>()
                                    .eq(DeadlineNode::getMainId, approval.getId())
                    );
                }
                // 6. 保留原有逻辑：批量插入节点（将收集的旧节点转为新节点格式插入）
                List<DeadlineNode> nodeList = new ArrayList<>();
                for (DeadlineNodeApproval approval : nodeApprovalList) {
                    DeadlineNode node = new DeadlineNode();
                    BeanUtils.copyProperties(approval, node);
                    nodeList.add(node);
                }
                if (!nodeList.isEmpty()) {
                    deadlineNodeMapper.batchInsert(nodeList); // 批量插入节点（原有核心步骤，不缺失）
                }
//                // 查询数据库中已存在的记录
//                List<TicketProblemInfo> existingInfos = ticketProblemInfoMapper.selectList(
//                        new LambdaQueryWrapper<TicketProblemInfo>()
//                                .eq(TicketProblemInfo::getRectificationId, rectificationInfoApproval.getRectificationId())
//                );
//
//                Map<String, TicketProblemInfo> existingDeptMap = existingInfos.stream()
//                        .collect(Collectors.toMap(
//                                info -> Optional.ofNullable(info.getProcessHandlerDepartment()).orElse("DEFAULT_NULL_KEY"),
//                                info -> info,
//                                (existing, replacement) -> existing,
//                                HashMap::new
//                        ));
//                List<DeadlineNodeApproval> nodeApprovalList = new ArrayList<>();
//                for (TicketProblemInfoApproval approval : ticketProblemInfoApprovalList) {
//                    // 统一处理审批信息中的部门null值，与数据库查询的处理保持一致
//                    String deptKey = Optional.ofNullable(approval.getProcessHandlerDepartment())
//                            .orElse("DEFAULT_NULL_KEY");
//
//                    // 检查该部门是否已存在
//                    if (!existingDeptMap.containsKey(deptKey)) {
//                        TicketProblemInfo newInfo = new TicketProblemInfo();
//                        BeanUtils.copyProperties(approval, newInfo);
//                        // 确保关联的整改ID正确设置
//                        newInfo.setRectificationId(rectificationInfoApproval.getRectificationId());
//                        ticketProblemInfoMapper.insert(newInfo);
//                    }
//                    List<DeadlineNodeApproval> deadlineNodeApprovals = deadlineNodeApprovalMapper.selectList(new LambdaQueryWrapper<DeadlineNodeApproval>()
//                            .eq(DeadlineNodeApproval::getMainId, approval.getId()).orderByAsc(DeadlineNodeApproval::getSort));
//                    nodeApprovalList.addAll(deadlineNodeApprovals);
//                    deadlineNodeMapper.delete(new LambdaQueryWrapper<DeadlineNode>()
//                            .eq(DeadlineNode::getMainId, approval.getId()));
//                }
//                List<DeadlineNode> nodeList = new ArrayList<>();
//                for (DeadlineNodeApproval approval : nodeApprovalList) {
//                    DeadlineNode node = new DeadlineNode();
//                    BeanUtils.copyProperties(approval, node);
//                    nodeList.add(node);
//                }
//                deadlineNodeMapper.batchInsert(nodeList);
            }
            RectificationInfo rectificationInfo = rectificationInfoMapper.selectById(rectificationInfoApproval.getRectificationId());
            if (rectificationInfo!=null){
                BeanUtils.copyProperties(rectificationInfoApproval,rectificationInfo);
                rectificationInfo.setId(rectificationInfoApproval.getRectificationId());
                rectificationInfo.setIsEdit(0);
                rectificationInfo.setState("待签收");
                rectificationInfoMapper.updateById(rectificationInfo);
            }else {
                RectificationInfo rectificationInfo1= new RectificationInfo();
                BeanUtils.copyProperties(rectificationInfoApproval,rectificationInfo1);
                rectificationInfo1.setId(rectificationInfoApproval.getRectificationId());
                rectificationInfo1.setIsEdit(0);
                rectificationInfo1.setState("待签收");
                rectificationInfoMapper.insert(rectificationInfo1);
            }
            rectificationInfoApproval.setApprovalState("1");
            rectificationInfoApprovalMapper.updateById(rectificationInfoApproval);
            return Answer.ok("成功通过");
        }else {
            return Answer.error("项目为空");
        }
    }

    @Override
    public Answer<Object> getWaitApproval(JSONObject reqJson) {
        String title = reqJson.getString("title");
        String areaName = reqJson.getString("areaName");
        String departmentName = reqJson.getString("departmentName");
        String personLiaible = reqJson.getString("personLiaible");
        String leadLeader = reqJson.getString("leadLeader");

        String projectType = reqJson.getString("projectType");
        String projectChildType = reqJson.getString("projectChildType");
        String projectChildCategoryType = reqJson.getString("projectChildCategoryType");

        String currentDepartment = reqJson.getString("currentDepartment");

        Integer pageSize = reqJson.getInteger("pageSize");
        Integer pageNum = reqJson.getInteger("pageNum");
        Page<RectificationInfoApproval> resultPage = new Page<>(pageNum, pageSize);


        List<RectificationInfoApproval> rectificationInfoApprovalList = rectificationInfoApprovalMapper.selectList(new LambdaQueryWrapper<RectificationInfoApproval>()
                .eq(RectificationInfoApproval::getApprovalState,"0").ne(RectificationInfoApproval::getState, "已关闭")
                .ne(RectificationInfoApproval::getState, "已销号").ne(RectificationInfoApproval::getState,"已退出")
                .like(RectificationInfoApproval::getState, "待审核")
                .orderByDesc(RectificationInfoApproval::getId));
        //过滤条件
        System.out.println("rectificationInfoApprovalList length "+rectificationInfoApprovalList.size());
        Stream<RectificationInfoApproval> stream = rectificationInfoApprovalList.stream();
        if (StrUtil.isNotBlank(departmentName)) {
            stream = stream.filter(item ->
                    item.getDepartmentName() != null &&
                            item.getDepartmentName().contains(departmentName));
        }
        if (StrUtil.isNotBlank(title)) {
            stream = stream.filter(item ->
                    item.getTitle() != null &&
                            item.getTitle().contains(title));
        }
        if (StrUtil.isNotBlank(areaName)) {
            stream = stream.filter(item ->
                    item.getAreaName() != null &&
                            item.getAreaName().contains(areaName));
        }
        if (StrUtil.isNotBlank(personLiaible)) {
            stream = stream.filter(item ->
                    item.getPersonLiaible() != null &&
                            item.getPersonLiaible().contains(personLiaible));
        }
        if (StrUtil.isNotBlank(leadLeader)) {
            stream = stream.filter(item ->
                    item.getLeadLeader() != null &&
                            item.getLeadLeader().contains(leadLeader));
        }

        if (StrUtil.isNotBlank(currentDepartment)) {
            stream = stream.filter(item ->
                    item.getCreatorUnit() != null &&
                            item.getCreatorUnit().contains(currentDepartment));
        }

        if (StrUtil.isNotBlank(projectType)) {
            stream = stream.filter(item ->
                    item.getProjectType() != null &&
                            item.getProjectType().contains(projectType));
        }

        if (StrUtil.isNotBlank(projectChildType)) {
            stream = stream.filter(item ->
                    item.getProjectChildType() != null &&
                            item.getProjectChildType().contains(projectChildType));
        }
        if (StrUtil.isNotBlank(projectChildCategoryType)) {
            stream = stream.filter(item ->
                    item.getProjectChildCategoryType() != null &&
                            item.getProjectChildCategoryType().contains(projectChildCategoryType));
        }

        rectificationInfoApprovalList = stream.collect(Collectors.toList());
        System.out.println("rectificationInfoApprovalList length "+rectificationInfoApprovalList.size());

        int total = rectificationInfoApprovalList.size();
        int pages = (total + pageSize - 1) / pageSize;

        if (pageNum > pages) {
            pageNum = pages;
        }
        if (pageNum < 1) {
            pageNum = 1;
        }

        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);

        System.out.println("rectificationInfoApprovalList length "+rectificationInfoApprovalList.size());

        // 使用子列表创建分页结果
        List<RectificationInfoApproval> pageRecords = rectificationInfoApprovalList.subList(fromIndex, toIndex);

        resultPage.setRecords(pageRecords);
        resultPage.setTotal(total);
        resultPage.setPages(pages);
        resultPage.setCurrent(pageNum);
        resultPage.setSize(pageSize);

        return Answer.ok(resultPage);
    }

    @Override
    public Answer<Object> getRectificationInfoApprovalList(JSONObject reqJson) {
        String title = reqJson.getString("title");
        String areaName = reqJson.getString("areaName");
        String departmentName = reqJson.getString("departmentName");
        String personLiaible = reqJson.getString("personLiaible");
        String leadLeader = reqJson.getString("leadLeader");

        String projectType = reqJson.getString("projectType");
        String projectChildType = reqJson.getString("projectChildType");
        String projectChildCategoryType = reqJson.getString("projectChildCategoryType");

        String currentDepartment = reqJson.getString("currentDepartment");

        Integer pageSize = reqJson.getInteger("pageSize");
        Integer pageNum = reqJson.getInteger("pageNum");
        Page<RectificationInfoApproval> resultPage = new Page<>(pageNum, pageSize);


        List<RectificationInfoApproval> rectificationInfoApprovalList = rectificationInfoApprovalMapper.selectList(new LambdaQueryWrapper<RectificationInfoApproval>()
                .eq(RectificationInfoApproval::getApprovalState,"0").ne(RectificationInfoApproval::getState, "已关闭")
                .ne(RectificationInfoApproval::getState, "已销号").ne(RectificationInfoApproval::getState,"已退出")
                .orderByDesc(RectificationInfoApproval::getId));
        //过滤条件
        Stream<RectificationInfoApproval> stream = rectificationInfoApprovalList.stream();
        if (StrUtil.isNotBlank(departmentName)) {
            stream = stream.filter(item ->
                    item.getDepartmentName() != null &&
                            item.getDepartmentName().contains(departmentName));
        }
        if (StrUtil.isNotBlank(title)) {
            stream = stream.filter(item ->
                    item.getTitle() != null &&
                            item.getTitle().contains(title));
        }
        if (StrUtil.isNotBlank(areaName)) {
            stream = stream.filter(item ->
                    item.getAreaName() != null &&
                            item.getAreaName().contains(areaName));
        }
        if (StrUtil.isNotBlank(personLiaible)) {
            stream = stream.filter(item ->
                    item.getPersonLiaible() != null &&
                            item.getPersonLiaible().contains(personLiaible));
        }
        if (StrUtil.isNotBlank(leadLeader)) {
            stream = stream.filter(item ->
                    item.getLeadLeader() != null &&
                            item.getLeadLeader().contains(leadLeader));
        }

        if (StrUtil.isNotBlank(currentDepartment)) {
            stream = stream.filter(item ->
                    item.getCreatorUnit() != null &&
                            item.getCreatorUnit().contains(currentDepartment));
        }

        if (StrUtil.isNotBlank(projectType)) {
            stream = stream.filter(item ->
                    item.getProjectType() != null &&
                            item.getProjectType().contains(projectType));
        }

        if (StrUtil.isNotBlank(projectChildType)) {
            stream = stream.filter(item ->
                    item.getProjectChildType() != null &&
                            item.getProjectChildType().contains(projectChildType));
        }
        if (StrUtil.isNotBlank(projectChildCategoryType)) {
            stream = stream.filter(item ->
                    item.getProjectChildCategoryType() != null &&
                            item.getProjectChildCategoryType().contains(projectChildCategoryType));
        }

        rectificationInfoApprovalList = stream.collect(Collectors.toList());

        int total = rectificationInfoApprovalList.size();
        int pages = (total + pageSize - 1) / pageSize;

        if (pageNum > pages) {
            pageNum = pages;
        }
        if (pageNum < 1) {
            pageNum = 1;
        }

        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = Math.min(fromIndex + pageSize, total);

        // 使用子列表创建分页结果
        List<RectificationInfoApproval> pageRecords = rectificationInfoApprovalList.subList(fromIndex, toIndex);

        resultPage.setRecords(pageRecords);
        resultPage.setTotal(total);
        resultPage.setPages(pages);
        resultPage.setCurrent(pageNum);
        resultPage.setSize(pageSize);

        return Answer.ok(resultPage);
    }

    @Override
    public Answer<Object> queryDeadlineNodeApprovalList(RectificationInfoApproval rectificationInfoApproval) {
        try {
            Integer id = rectificationInfoApproval.getId();
            if (id == null) {
                return Answer.error("id不能为空");
            }
            RectificationInfoApproval rectificationInfoApproval1 = rectificationInfoApprovalMapper.selectOne(new LambdaQueryWrapper<RectificationInfoApproval>()
                    .eq(RectificationInfoApproval::getId,id));
            RectificationInfo rectificationInfo = rectificationInfoMapper.selectById(rectificationInfoApproval1.getRectificationId());
            if (rectificationInfoApproval1 == null) {
                if (rectificationInfo == null) {
                    return Answer.error("项目为空");
                }
            }
            List<DeadlineNodeApproval> deadlineNodeList = deadlineNodeApprovalMapper.selectList(new LambdaQueryWrapper<DeadlineNodeApproval>()
                    .eq(DeadlineNodeApproval::getRectificationId, rectificationInfoApproval1.getRectificationId()).orderByAsc(DeadlineNodeApproval::getSort));
                if (rectificationInfoApproval1.getProjectChildType() != null) {
                    if (rectificationInfoApproval1.getProjectChildType().contains("主城崛起") || rectificationInfoApproval1.getProjectChildType().equals("项目建设")) {
                        if (deadlineNodeList != null && !deadlineNodeList.isEmpty()) {
                            // 寻找三个节点的位置
                            int firstDesignIndex = -1;
                            int huanIndex = -1;
                            int anIndex = -1;
                            for (int i = 0; i < deadlineNodeList.size(); i++) {
                                DeadlineNodeApproval node = deadlineNodeList.get(i);
                                String nodeName = node.getName();

                                if ("完成初步设计批复".equals(nodeName)) {
                                    firstDesignIndex = i;
                                } else if ("完成环评批复".equals(nodeName)) {
                                    huanIndex = i;
                                } else if ("完成安评手续".equals(nodeName)) {
                                    anIndex = i;
                                }
                            }

                            // 只有当三个节点都存在时才进行调整
                            if (firstDesignIndex != -1 && huanIndex != -1 && anIndex != -1) {
                                // 保存三个节点的引用
                                DeadlineNodeApproval firstNode = deadlineNodeList.get(firstDesignIndex);
                                DeadlineNodeApproval huanNode = deadlineNodeList.get(huanIndex);
                                DeadlineNodeApproval anNode = deadlineNodeList.get(anIndex);

                                // 创建新列表，先添加所有节点
                                List<DeadlineNodeApproval> tempList = new ArrayList<>();
                                for (DeadlineNodeApproval node : deadlineNodeList) {
                                    // 跳过需要重新排序的三个节点
                                    if (node != firstNode && node != huanNode && node != anNode) {
                                        tempList.add(node);
                                    }
                                }

                                // 找到原列表中三个节点最早出现的位置
                                int insertPos = Math.min(firstDesignIndex, Math.min(huanIndex, anIndex));

                                // 插入调整后的节点顺序：初步设计 -> 环评 -> 安评
                                tempList.add(insertPos, firstNode);
                                tempList.add(insertPos + 1, huanNode);
                                tempList.add(insertPos + 2, anNode);

                                // 更新原列表
                                deadlineNodeList.clear();
                                deadlineNodeList.addAll(tempList);
                            }
                        }
                    }
                }
                deadlineNodeList = filiterNode(rectificationInfoApproval1, deadlineNodeList);
                return Answer.ok(deadlineNodeList);
        } catch (Exception e) {
            e.printStackTrace();
            return Answer.error("查询失败");
        }
    }

    private List<DeadlineNodeApproval> filiterNode(RectificationInfoApproval rectificationInfo, List<DeadlineNodeApproval> deadlineNodeList) {
        if (CollectionUtil.isEmpty(deadlineNodeList)) {
            return deadlineNodeList;
        }
        // 根据项目类型和分类类型过滤节点
//        boolean needFilter = (
//                (rectificationInfo.getProjectChildType().contains("主城崛起") &&
//                        rectificationInfo.getProjectChildCategoryType().contains("招商签约未开工重点项目")) ||
//                        ("招商引资".equals(rectificationInfo.getProjectChildType()) &&
//                                "签约未开工重点项目".equals(rectificationInfo.getProjectChildCategoryType()))
//        );
//
//        if (needFilter) {
//            List<String> allowedLinks = Arrays.asList(
//                    "生成项目（签约）",
//                    "纳入上级规划/纳入年度投资计划/完成项目建议书批复，启动项目实施",
//                    "完成规划选址",
//                    "完成环评批复",
//                    "完成安评手续",
//                    "完成用地手续批复（用地、工程规划许可证）",
//                    "完成用林手续批复",
//                    "完成项目招投标（含公示）",
//                    "办理施工许可证并开工建设"
//            );
//            deadlineNodeList = deadlineNodeList.stream()
//                    .filter(node -> allowedLinks.contains(node.getName()))
//                    .collect(Collectors.toList());
//        }
//
//        boolean needFilter2 = (
//                (rectificationInfo.getProjectChildType().contains("主城崛起") &&
//                        rectificationInfo.getProjectChildCategoryType().contains("拟开工重点项目"))
//                        ||
//                        ("项目建设".equals(rectificationInfo.getProjectChildType()) && "拟开工重点项目".equals(rectificationInfo.getProjectChildCategoryType()))
//        );
//
//        if (needFilter2) {
//            List<String> allowedLinks = Arrays.asList(
//                    "纳入上级规划/纳入年度投资计划/完成项目建议书批复，启动项目实施",
//                    "完成可行性研究报告批复",
//                    "完成环评批复",
//                    "完成安评手续",
//                    "完成初步设计批复",
//                    "完成财政预算评审",
//                    "完成用地手续批复（用地、工程规划许可证）",
//                    "完成用林手续批复",
//                    "完成项目招投标（含公示）",
//                    "办理施工许可证并开工建设"
//            );
//            deadlineNodeList = deadlineNodeList.stream()
//                    .filter(node -> allowedLinks.contains(node.getName()))
//                    .collect(Collectors.toList());
//        }

        // 排除 progress 为 / 的节点
        return deadlineNodeList.stream()
                .filter(node -> node.getProgress() == null || !"/".equals(node.getProgress()))
                .collect(Collectors.toList());
    }

    @Override
    public Answer<Object> queryTicketProblemApprovalList(RectificationInfoApproval rectificationInfoApproval) {
        try {
            JSONArray resList = new JSONArray();
            Integer id = rectificationInfoApproval.getId();
            if (id == null) {
                return Answer.error("id不能为空");
            }
            RectificationInfoApproval rectificationInfoRes = rectificationInfoApprovalMapper.selectById(id);
            if (rectificationInfoRes == null) {
                return Answer.error("id不存在");
            }
            List<TicketProblemInfoApproval> ticketProblemInfoList = ticketProblemInfoApprovalMapper.selectList(new LambdaQueryWrapper<TicketProblemInfoApproval>()
                    .eq(TicketProblemInfoApproval::getRectificationId, rectificationInfoRes.getRectificationId()));
            if (ticketProblemInfoList == null) {
                return Answer.error("问题清单不存在");
            }
            List<String> departmentNameList = ticketProblemInfoList.stream().map(TicketProblemInfoApproval::getProcessHandlerDepartment)
                    .distinct().filter(StrUtil::isNotBlank).collect(Collectors.toList());
            if (CollectionUtil.isEmpty(departmentNameList)) {
                return Answer.error("处理部门不存在");
            }
            for (String departmentName : departmentNameList) {
                JSONObject resJson = new JSONObject();
                List<TicketProblemInfoApproval> collect = ticketProblemInfoList.stream()
                        .filter(TicketProblemInfoApproval -> departmentName.equals(TicketProblemInfoApproval.getProcessHandlerDepartment()))
                        .collect(Collectors.toList());
                Integer mainId = collect.get(0).getId();
                List<DeadlineNodeApproval> deadlineNodeList = deadlineNodeApprovalMapper.selectList(new LambdaQueryWrapper<DeadlineNodeApproval>()
                        .eq(DeadlineNodeApproval::getMainId,mainId));
                for (DeadlineNodeApproval deadlineNodeApproval:deadlineNodeList){
                    deadlineNodeApproval.setDepartmentName(departmentName);
                }
                resJson.put("departmentName", departmentName);
                resJson.put("deadlineNodeList", deadlineNodeList);
                resList.add(resJson);
            }
            return Answer.ok(resList);
        } catch (Exception e) {
            e.printStackTrace();
            return Answer.error("查询失败");
        }
    }

    @Override
    public Answer<Object> accountTermination(RectificationInfoApproval rectificationInfoApproval) {
        Integer rectificationId = rectificationInfoApproval.getRectificationId();
        if (rectificationId==null){
            return Answer.error("项目id不能为空");
        }
        RectificationInfoApproval rectificationInfoApproval1 = rectificationInfoApprovalMapper.selectOne(new LambdaQueryWrapper<RectificationInfoApproval>()
                .eq(RectificationInfoApproval::getRectificationId,rectificationId).eq(RectificationInfoApproval::getApprovalState,0)
                .ne(RectificationInfoApproval::getState,"已关闭").ne(RectificationInfoApproval::getState,"已销号").ne(RectificationInfoApproval::getState,"已退出"));
        if (rectificationInfoApproval1!=null){
            rectificationInfoApproval1.setApprovalState("0");
            rectificationInfoApproval1.setState("提交销号待审核");
            rectificationInfoApproval1.setApplyReason(rectificationInfoApproval.getApplyReason());
            rectificationInfoApproval1.setApprovalUrl(rectificationInfoApproval.getApprovalUrl());
            rectificationInfoApproval1.setLastOperationTime(new Date());
            rectificationInfoApprovalMapper.updateById(rectificationInfoApproval1);
        }else {
            RectificationInfoApproval rectificationInfoApproval2 = new RectificationInfoApproval();
            RectificationInfo rectificationInfo = rectificationInfoMapper.selectById(rectificationId);
            BeanUtils.copyProperties(rectificationInfo,rectificationInfoApproval2);
            rectificationInfoApproval2.setApprovalState("0");
            rectificationInfoApproval2.setState("提交销号待审核");
            rectificationInfoApproval2.setRectificationId(rectificationInfo.getId());
            rectificationInfoApproval2.setApplyReason(rectificationInfoApproval.getApplyReason());
            rectificationInfoApproval2.setApprovalUrl(rectificationInfoApproval.getApprovalUrl());
            rectificationInfoApproval2.setLastOperationTime(new Date());
            rectificationInfoApproval2.setId(null);
            rectificationInfoApprovalMapper.insert(rectificationInfoApproval2);
        }
        return Answer.ok("提交销号成功");
    }

    @Override
    public Answer<Object> exit(RectificationInfoApproval rectificationInfoApproval) {
        Integer rectificationId = rectificationInfoApproval.getRectificationId();
        if (rectificationId==null){
            return Answer.error("项目id不能为空");
        }
        RectificationInfoApproval rectificationInfoApproval1 = rectificationInfoApprovalMapper.selectOne(new LambdaQueryWrapper<RectificationInfoApproval>()
                .eq(RectificationInfoApproval::getRectificationId,rectificationId).eq(RectificationInfoApproval::getApprovalState,0)
                .ne(RectificationInfoApproval::getState,"已关闭").ne(RectificationInfoApproval::getState,"已销号").ne(RectificationInfoApproval::getState,"已退出"));
        if (rectificationInfoApproval1!=null){
            rectificationInfoApproval1.setApprovalState("0");
            rectificationInfoApproval1.setState("提交退出待审核");
            rectificationInfoApproval1.setApplyReason(rectificationInfoApproval.getApplyReason());
            rectificationInfoApproval1.setLastOperationTime(new Date());
            rectificationInfoApproval1.setApprovalUrl(rectificationInfoApproval.getApprovalUrl());
            rectificationInfoApprovalMapper.updateById(rectificationInfoApproval1);
        }else {
            RectificationInfoApproval rectificationInfoApproval2 = new RectificationInfoApproval();
            RectificationInfo rectificationInfo = rectificationInfoMapper.selectById(rectificationId);
            BeanUtils.copyProperties(rectificationInfo,rectificationInfoApproval2);
            rectificationInfoApproval2.setApprovalState("0");
            rectificationInfoApproval2.setState("提交退出待审核");
            rectificationInfoApproval2.setRectificationId(rectificationInfo.getId());
            rectificationInfoApproval2.setApplyReason(rectificationInfoApproval.getApplyReason());
            rectificationInfoApproval2.setLastOperationTime(new Date());
            rectificationInfoApproval2.setApprovalUrl(rectificationInfoApproval.getApprovalUrl());
            rectificationInfoApproval2.setId(null);
            rectificationInfoApprovalMapper.insert(rectificationInfoApproval2);
        }
        return Answer.ok("提交退出成功");
    }

    @Override
    public Answer<Object> passAccountTermination(JSONObject reqJson) {
        Integer id = reqJson.getInteger("id");
        if (id==null){
            return Answer.error("项目id为空");
        }
        RectificationInfoApproval rectificationInfoApproval = rectificationInfoApprovalMapper.selectOne(new LambdaQueryWrapper<RectificationInfoApproval>()
                .eq(RectificationInfoApproval::getId,id));
        String state = reqJson.getString("state");
        System.out.println("passAccountTermination_ state = : "+state);
        if (state!= null && state.equals("不通过")){
            rectificationInfoApproval.setApprovalState("2");
            rectificationInfoApproval.setState("销号申请不通过");
            rectificationInfoApproval.setLastOperationTime(new Date());
            rectificationInfoApprovalMapper.updateById(rectificationInfoApproval);
            return Answer.ok("审核不通过");
        }
        if (rectificationInfoApproval!=null) {
            RectificationInfo rectificationInfo = rectificationInfoMapper.selectById(rectificationInfoApproval.getRectificationId());
            if (rectificationInfo!=null) {
                BeanUtils.copyProperties(rectificationInfoApproval, rectificationInfo);
                rectificationInfo.setState("已销号");
                rectificationInfo.setLastOperationTime(new Date());
                rectificationInfo.setId(rectificationInfoApproval.getRectificationId());
                rectificationInfoMapper.updateById(rectificationInfo);
            }else {
                RectificationInfo rectificationInfo1 = new RectificationInfo();
                BeanUtils.copyProperties(rectificationInfoApproval, rectificationInfo1);
                rectificationInfo.setState("已销号");
                rectificationInfo.setLastOperationTime(new Date());
                rectificationInfo1.setId(null);
                rectificationInfoMapper.insert(rectificationInfo);
            }
            rectificationInfoApproval.setApprovalState("1");
            rectificationInfoApproval.setState("已销号");
            rectificationInfoApproval.setLastOperationTime(new Date());
            rectificationInfoApprovalMapper.updateById(rectificationInfoApproval);
            return Answer.ok("成功销号");
        }else {
            return Answer.error("项目为空");
        }
    }

    @Override
    public Answer<Object> approvalExit(JSONObject reqJson) {
        Integer id = reqJson.getInteger("id");
        if (id==null){
            return Answer.error("项目id为空");
        }
        RectificationInfoApproval rectificationInfoApproval = rectificationInfoApprovalMapper.selectOne(new LambdaQueryWrapper<RectificationInfoApproval>()
                .eq(RectificationInfoApproval::getId,id));

        if (rectificationInfoApproval!=null) {
            RectificationInfo rectificationInfo = rectificationInfoMapper.selectById(rectificationInfoApproval.getRectificationId());
            if (rectificationInfo!=null) {
                BeanUtils.copyProperties(rectificationInfoApproval, rectificationInfo);
                rectificationInfo.setState("已退出");
                rectificationInfo.setLastOperationTime(new Date());
                rectificationInfo.setId(rectificationInfoApproval.getRectificationId());
                rectificationInfoMapper.updateById(rectificationInfo);
            }else {
                RectificationInfo rectificationInfo1 = new RectificationInfo();
                BeanUtils.copyProperties(rectificationInfoApproval, rectificationInfo1);
                rectificationInfo.setState("已退出");
                rectificationInfo.setLastOperationTime(new Date());
                rectificationInfo1.setId(null);
                rectificationInfoMapper.insert(rectificationInfo);
            }
            rectificationInfoApproval.setApprovalState("1");
            rectificationInfoApproval.setState("已退出");
            rectificationInfoApproval.setLastOperationTime(new Date());
            rectificationInfoApprovalMapper.updateById(rectificationInfoApproval);
            return Answer.ok("成功退出");
        }else {
            return Answer.error("项目为空");
        }
    }

    @Override
    public Answer<Object> updateDeadlineNodeApproval(JSONObject reqJson) {
        String deadlineType = reqJson.getString("deadlineType");
        String description = reqJson.getString("description");
        Integer duration = reqJson.getInteger("duration");
        Date endTime = reqJson.getDate("endTime");
        String progress = reqJson.getString("progress");
        String remark = reqJson.getString("remark");
        Integer id = reqJson.getInteger("id");
        DeadlineNodeApproval deadlineNodeApproval = deadlineNodeApprovalMapper.selectById(id);
        if (deadlineNodeApproval!=null){
            if (StringUtils.isNotBlank(deadlineType)) {
                deadlineNodeApproval.setDeadlineType(deadlineType);
            }
            if (StringUtils.isNotBlank(description)) {
                deadlineNodeApproval.setDescription(description);
            }
            if (description!=null) {
                deadlineNodeApproval.setDuration(duration);
            }
            if (endTime!=null) {
                deadlineNodeApproval.setEndTime(endTime);
            }
            if (StringUtils.isNotBlank(progress)) {
                deadlineNodeApproval.setProgress(progress);
            }
            if (StringUtils.isNotBlank(remark)) {
                deadlineNodeApproval.setRemark(remark);
            }
            deadlineNodeApproval.setState("更新待审核");
            deadlineNodeApprovalMapper.updateById(deadlineNodeApproval);
        }else {
            DeadlineNodeApproval nodeApproval = new DeadlineNodeApproval();
            nodeApproval.setId(id);
            if (StringUtils.isNotBlank(deadlineType)) {
                nodeApproval.setDeadlineType(deadlineType);
            }
            if (StringUtils.isNotBlank(description)) {
                nodeApproval.setDescription(description);
            }
            if (description!=null) {
                nodeApproval.setDuration(duration);
            }
            if (endTime!=null) {
                nodeApproval.setEndTime(endTime);
            }
            if (StringUtils.isNotBlank(progress)) {
                nodeApproval.setProgress(progress);
            }
            if (StringUtils.isNotBlank(remark)) {
                nodeApproval.setRemark(remark);
            }
            deadlineNodeApproval.setState("更新待审核");
            deadlineNodeApprovalMapper.insert(nodeApproval);
        }


        return Answer.ok("更新成功");
    }

    @Override
    public Answer<Object> passDeadlineNodeApproval(JSONObject reqJson) {
        Integer id = reqJson.getInteger("id");

        DeadlineNodeApproval deadlineNodeApproval = deadlineNodeApprovalMapper.selectById(id);
        if (deadlineNodeApproval!=null){
            DeadlineNode deadlineNode =new DeadlineNode();
            BeanUtils.copyProperties(deadlineNodeApproval,deadlineNode);
            deadlineNode.setState("审核待签收");
            deadlineNodeMapper.updateById(deadlineNode);
            return Answer.ok("审批完成");
        }else {
            return Answer.error("节点不存在");
        }
    }
    @Override
    public Answer<Object> deleteApproval(Integer id) {
        int ret = rectificationInfoApprovalMapper.deleteById(id);
        return Answer.ok("删除成功");
    }

    @Override
    public Answer<Object> add(RectificationInfoApproval rectificationInfoApproval) {
        Date date = new Date();
        //项目名称
        String title = rectificationInfoApproval.getTitle();
        if (StrUtil.isBlank(title)) {
            return Answer.error("项目名称不能为空");
        }

        //项目简介
        String content = rectificationInfoApproval.getContent();
        if (StrUtil.isBlank(content)) {
            return Answer.error("项目简介不能为空");
        }

        //牵头单位
        String leadUnit = rectificationInfoApproval.getLeadUnit();
        if (StrUtil.isBlank(leadUnit)) {
            return Answer.error("牵头单位不能为空");
        }

        //工作类型
        String projectType = rectificationInfoApproval.getProjectType();
        if (StrUtil.isBlank(projectType)) {
            return Answer.error("工作类型不能为空");
        }

        //牵头领导
        String leadLeader = rectificationInfoApproval.getLeadLeader();
        if (StrUtil.isBlank(leadLeader)) {
            return Answer.error("牵头领导不能为空");
        }

        //责任人
        String personLiaible = rectificationInfoApproval.getPersonLiaible();
        if (StrUtil.isBlank(personLiaible)) {
            return Answer.error("责任人不能为空");
        }

        //项目要求完成时间
        Date deadline = rectificationInfoApproval.getDeadline();
//        if (deadline == null) {
//            return Answer.error("项目要求完成时间不能为空");
//        }


        String[] split = projectType.split("/");
        rectificationInfoApproval.setApprovalState("0");
        rectificationInfoApproval.setRectificationId(generateNumericId());
        rectificationInfoApproval.setProjectType(split[0]);
        rectificationInfoApproval.setProjectChildType(split[1]);
        if (split.length>2){
            rectificationInfoApproval.setProjectChildCategoryType(split[2]);
        }
        rectificationInfoApproval.setCheckRemark(rectificationInfoApproval.getCheckRemark());
        rectificationInfoApproval.setState("待提交");


        //List<ProblemSummaryInfo> problemSummaryInfoList = problemSummaryInfoMapper.selectList(new LambdaQueryWrapper<ProblemSummaryInfo>().eq(ProblemSummaryInfo::getProjectName, projectType));
        Integer summaryId = 1;
        TaskInfo taskInfo = new TaskInfo();
        taskInfo.setContent(content);
        taskInfo.setName(content);
        taskInfo.setSummaryId(summaryId);
        taskInfo.setCreateTime(date);
        //TaskInfo lastTaskInfo = taskInfoMapper.selectOne(new LambdaQueryWrapper<TaskInfo>().eq(TaskInfo::getSummaryId, summaryId).isNotNull(TaskInfo::getSort).orderByDesc(TaskInfo::getSort).last("LIMIT 1"));
        taskInfo.setSort(1);
        taskInfoMapper.insert(taskInfo);


        Task1Info task1Info = new Task1Info();
        task1Info.setTaskId(taskInfo.getId());
        task1Info.setContent(content);
        task1Info.setName(content);
        task1Info.setCreateTime(date);
        //Task1Info lastTask1Info = task1InfoMapper.selectOne(new LambdaQueryWrapper<Task1Info>().eq(Task1Info::getTaskId, taskInfo.getId()).isNotNull(Task1Info::getSort).orderByDesc(Task1Info::getSort).last("LIMIT 1"));
        task1Info.setSort(1);
        task1InfoMapper.insert(task1Info);


        Task2Info task2Info = new Task2Info();
        task2Info.setTask1Id(task1Info.getId());
        task2Info.setContent(content);
        task2Info.setName(title);
        task2Info.setCreateTime(date);
        task2Info.setSort(1);
        task2InfoMapper.insert(task2Info);
        rectificationInfoApproval.setIsEdit(1);
        rectificationInfoApproval.setSummaryId(summaryId);
        rectificationInfoApproval.setTask2Id(task2Info.getId());
        rectificationInfoApprovalMapper.insert(rectificationInfoApproval);
        if (rectificationInfoApproval.getProjectType().equals("高质量发展")){
            if(rectificationInfoApproval.getProjectChildCategoryType()!=null){
                List<String> targetTypes = Arrays.asList(
                        "拟开工重点项目",
                        "谋划推进重大项目",
                        "签约未开工重点项目",
                        "招商签约未开工重点项目",
                        "谋划重大项目"
                );
                // 2. 获取当前类型并判空，用 Stream 流判断是否存在模糊匹配
                String currentType = rectificationInfoApproval.getProjectChildCategoryType();
                boolean isMatch = Optional.ofNullable(currentType) // 处理null，避免空指针
                        .filter(type -> !type.trim().isEmpty()) // 过滤空字符串（可选，根据业务需求）
                        .map(type -> targetTypes.stream()
                                .anyMatch(targetType -> type.contains(targetType)) // 核心：任意一个目标类型被包含即匹配
                        ).orElse(false); // 若currentType为null或空，默认返回false
                // 3. 后续逻辑（同上）
                if (isMatch) {
                    // 满足条件的业务处理
                    DateTime dateTime = DateUtil.date(deadline);
                    nodeList(rectificationInfoApproval, dateTime);
                }
            }
        }
        return Answer.ok("添加成功");
    }

    private static final String NUMBERS = "0123456789";
    // 字母数字混合字符集（包含大小写字母和数字）

    private static final Random random = new Random();

    public static Integer generateNumericId() {
        StringBuilder sb = new StringBuilder(6);
        for (int i = 0; i < 6; i++) {
            // 从数字字符集中随机选择一个字符
            int index = random.nextInt(NUMBERS.length());
            sb.append(NUMBERS.charAt(index));
        }
        return Integer.valueOf(sb.toString());
    }

    @Transactional
    public String nodeList(RectificationInfoApproval rectificationInfoApproval, DateTime deadline) {
        List<DeadlineNode> deadlineNodes = new ArrayList<>();
        //生成项目（签约）
        DeadlineNode deadlineNode = new DeadlineNode();
        deadlineNode.setMainId(rectificationInfoApproval.getId());//mainId
//        deadlineNode.setDeadline(deadline);
        deadlineNode.setSort(0);
        deadlineNode.setCreateTime(new Date());
        deadlineNode.setName("生成项目（签约）");
//        deadlineNode.setDeadlineType("责任人");
        deadlineNode.setTypeName("整改");
        deadlineNode.setIsEnd("0");
        deadlineNode.setRectificationId(rectificationInfoApproval.getRectificationId());
        deadlineNode.setWarnLevel("0");
//        deadlineNode.setDepartmentName("部门");
//        deadlineNode.setDeadlineType("0d");
        deadlineNodes.add(deadlineNode);
        //纳入上级规划/纳入年度投资计划/完成项目建议书批复，启动项目实施
        DeadlineNode deadlineNode1 = new DeadlineNode();
        deadlineNode1.setMainId(rectificationInfoApproval.getId());//mainId
        deadlineNode1.setDeadline(deadline);
        deadlineNode1.setSort(1);
        deadlineNode1.setCreateTime(new Date());
        deadlineNode1.setName("纳入上级规划/纳入年度投资计划/完成项目建议书批复，启动项目实施");
        deadlineNode1.setDescription(responsiblePersonsService.locatePerson(deadlineNode1.getName(), rectificationInfoApproval.getLeadUnit()));
        deadlineNode1.setTypeName("整改");
        deadlineNode1.setIsEnd("0");
        deadlineNode1.setWarnLevel("0");
        deadlineNode1.setRectificationId(rectificationInfoApproval.getRectificationId());
        deadlineNode1.setDepartmentName("发改部门");
        deadlineNode1.setDeadlineType("0d");
        deadlineNode1.setState("1");
        deadlineNodes.add(deadlineNode1);
        //完成可行性研究报告批复
        DeadlineNode deadlineNode2 = new DeadlineNode();
        deadlineNode2.setMainId(rectificationInfoApproval.getId());//mainId
        deadlineNode2.setDeadline(calculateFutureDate(deadline, 30));
        deadlineNode2.setSort(2);
        deadlineNode2.setRectificationId(rectificationInfoApproval.getRectificationId());
        deadlineNode2.setCreateTime(new Date());
        deadlineNode2.setName("完成可行性研究报告批复");
        deadlineNode2.setDescription(responsiblePersonsService.locatePerson(deadlineNode2.getName(), rectificationInfoApproval.getLeadUnit()));
        deadlineNode2.setTypeName("整改");
        deadlineNode2.setIsEnd("0");
        deadlineNode2.setWarnLevel("0");
        deadlineNode2.setDepartmentName("发改部门");
        deadlineNode2.setDeadlineType("30d");
        deadlineNode2.setState("1");
        deadlineNodes.add(deadlineNode2);
        //完成规划选址
        DeadlineNode deadlineNode3 = new DeadlineNode();
        deadlineNode3.setMainId(rectificationInfoApproval.getId());//mainId
//        deadlineNode3.setDeadline(deadline);
        deadlineNode3.setSort(3);
        deadlineNode3.setCreateTime(new Date());
        deadlineNode3.setRectificationId(rectificationInfoApproval.getRectificationId());
        deadlineNode3.setName("完成规划选址");
//        deadlineNode3.setDescription("负责人");
        deadlineNode3.setTypeName("整改");
        deadlineNode3.setIsEnd("0");
        deadlineNode3.setWarnLevel("0");
        deadlineNode3.setDepartmentName("项目招引单位");
        deadlineNode3.setState("1");
//        deadlineNode3.setDeadlineType("30d");
        deadlineNodes.add(deadlineNode3);
        //完成环评批复
        DeadlineNode deadlineNode4 = new DeadlineNode();
        deadlineNode4.setMainId(rectificationInfoApproval.getId());//mainId
        deadlineNode4.setDeadline(calculateFutureDate(deadline, 60));
        deadlineNode4.setSort(4);
        deadlineNode4.setCreateTime(new Date());
        deadlineNode4.setName("完成环评批复");
        deadlineNode4.setDescription(responsiblePersonsService.locatePerson(deadlineNode4.getName(), rectificationInfoApproval.getLeadUnit()));
        deadlineNode4.setTypeName("整改");
        deadlineNode4.setIsEnd("0");
        deadlineNode4.setRectificationId(rectificationInfoApproval.getRectificationId());
        deadlineNode4.setWarnLevel("0");
        deadlineNode4.setDepartmentName("生态环境部门");
        deadlineNode4.setDeadlineType("60d");
        deadlineNode4.setState("1");
        deadlineNodes.add(deadlineNode4);
        //完成安评手续
        DeadlineNode deadlineNode5 = new DeadlineNode();
        deadlineNode5.setMainId(rectificationInfoApproval.getId());//mainId
        deadlineNode5.setDeadline(calculateFutureDate(deadline, 60));
        deadlineNode5.setSort(5);
        deadlineNode5.setCreateTime(new Date());
        deadlineNode5.setName("完成安评手续");
        deadlineNode5.setDescription(responsiblePersonsService.locatePerson(deadlineNode5.getName(), rectificationInfoApproval.getLeadUnit()));
        deadlineNode5.setTypeName("整改");
        deadlineNode5.setIsEnd("0");
        deadlineNode5.setRectificationId(rectificationInfoApproval.getRectificationId());
        deadlineNode5.setWarnLevel("0");
        deadlineNode5.setDepartmentName("应急管理部门");
        deadlineNode5.setDeadlineType("60d");
        deadlineNode5.setState("1");
        deadlineNodes.add(deadlineNode5);
        //完成初步设计批复
        DeadlineNode deadlineNode6 = new DeadlineNode();
        deadlineNode6.setMainId(rectificationInfoApproval.getId());//mainId
        deadlineNode6.setDeadline(calculateFutureDate(deadline, 60));
        deadlineNode6.setSort(6);
        deadlineNode6.setCreateTime(new Date());
        deadlineNode6.setName("完成初步设计批复");
        deadlineNode6.setDescription(responsiblePersonsService.locatePerson(deadlineNode6.getName(), rectificationInfoApproval.getLeadUnit()));
        deadlineNode6.setTypeName("整改");
        deadlineNode6.setIsEnd("0");
        deadlineNode6.setWarnLevel("0");
        deadlineNode6.setDepartmentName("发改部门");
        deadlineNode6.setRectificationId(rectificationInfoApproval.getRectificationId());
        deadlineNode6.setDeadlineType("60d");
        deadlineNode6.setState("1");
        deadlineNodes.add(deadlineNode6);
        //完成财政预算评审
        DeadlineNode deadlineNode7 = new DeadlineNode();
        deadlineNode7.setMainId(rectificationInfoApproval.getId());//mainId
        deadlineNode7.setDeadline(calculateFutureDate(deadline, 120));
        deadlineNode7.setSort(7);
        deadlineNode7.setCreateTime(new Date());
        deadlineNode7.setName("完成财政预算评审");
        deadlineNode7.setDescription(responsiblePersonsService.locatePerson(deadlineNode7.getName(), rectificationInfoApproval.getLeadUnit()));
        deadlineNode7.setTypeName("整改");
        deadlineNode7.setIsEnd("0");
        deadlineNode7.setWarnLevel("0");
        deadlineNode7.setRectificationId(rectificationInfoApproval.getRectificationId());
        deadlineNode7.setDepartmentName("财政部门");
        deadlineNode7.setDeadlineType("120d");
        deadlineNode7.setState("1");
        deadlineNodes.add(deadlineNode7);
        //完成用地手续批复（用地、工程规划许可证）
        DeadlineNode deadlineNode8 = new DeadlineNode();
        deadlineNode8.setMainId(rectificationInfoApproval.getId());//mainId
        deadlineNode8.setDeadline(calculateFutureDate(deadline, 120));
        deadlineNode8.setSort(8);
        deadlineNode8.setCreateTime(new Date());
        deadlineNode8.setName("完成用地手续批复（用地、工程规划许可证）");
        deadlineNode8.setDescription(responsiblePersonsService.locatePerson(deadlineNode8.getName(), rectificationInfoApproval.getLeadUnit()));
        deadlineNode8.setTypeName("整改");
        deadlineNode8.setIsEnd("0");
        deadlineNode8.setRectificationId(rectificationInfoApproval.getRectificationId());
        deadlineNode8.setWarnLevel("0");
        deadlineNode8.setDepartmentName("资建部门");
        deadlineNode8.setDeadlineType("120d");
        deadlineNode8.setState("1");
        deadlineNodes.add(deadlineNode8);
        //完成用林手续批复
        DeadlineNode deadlineNode9 = new DeadlineNode();
        deadlineNode9.setMainId(rectificationInfoApproval.getId());//mainId
        deadlineNode9.setDeadline(calculateFutureDate(deadline, 120));
        deadlineNode9.setSort(9);
        deadlineNode9.setCreateTime(new Date());
        deadlineNode9.setName("完成用林手续批复");
        deadlineNode9.setDescription(responsiblePersonsService.locatePerson(deadlineNode9.getName(), rectificationInfoApproval.getLeadUnit()));
        deadlineNode9.setTypeName("整改");
        deadlineNode9.setIsEnd("0");
        deadlineNode9.setRectificationId(rectificationInfoApproval.getRectificationId());
        deadlineNode9.setWarnLevel("0");
        deadlineNode9.setDepartmentName("林业部门");
        deadlineNode9.setDeadlineType("120d");
        deadlineNode9.setState("1");
        deadlineNodes.add(deadlineNode9);
        //完成项目招投标（含公示）
        DeadlineNode deadlineNode10 = new DeadlineNode();
        deadlineNode10.setMainId(rectificationInfoApproval.getId());//mainId
        deadlineNode10.setDeadline(calculateFutureDate(deadline, 150));
        deadlineNode10.setSort(10);
        deadlineNode10.setCreateTime(new Date());
        deadlineNode10.setName("完成项目招投标（含公示）");
        deadlineNode10.setDescription(responsiblePersonsService.locatePerson(deadlineNode10.getName(), rectificationInfoApproval.getLeadUnit()));
        deadlineNode10.setTypeName("整改");
        deadlineNode10.setIsEnd("0");
        deadlineNode10.setWarnLevel("0");
        deadlineNode10.setRectificationId(rectificationInfoApproval.getRectificationId());
        deadlineNode10.setDepartmentName("项目单位");
        deadlineNode10.setDeadlineType("150d");
        deadlineNode10.setState("1");
        deadlineNodes.add(deadlineNode10);
        //办理施工许可证并开工建设
        DeadlineNode deadlineNode11 = new DeadlineNode();
        deadlineNode11.setMainId(rectificationInfoApproval.getId());//mainId
        deadlineNode11.setDeadline(calculateFutureDate(deadline, 180));
        deadlineNode11.setSort(11);
        deadlineNode11.setCreateTime(new Date());
        deadlineNode11.setName("办理施工许可证并开工建设");
        deadlineNode11.setDescription(responsiblePersonsService.locatePerson(deadlineNode11.getName(), rectificationInfoApproval.getLeadUnit()));
        deadlineNode11.setTypeName("整改");
        deadlineNode11.setIsEnd("0");
        deadlineNode11.setRectificationId(rectificationInfoApproval.getRectificationId());
        deadlineNode11.setWarnLevel("0");
        deadlineNode11.setDepartmentName("资建部门");
        deadlineNode11.setDeadlineType("180d");
        deadlineNode11.setState("1");
        deadlineNodes.add(deadlineNode11);
        List<DeadlineNodeApproval> deadlineNodeApprovalList = new ArrayList<>();
        for (DeadlineNode node:deadlineNodes){
            DeadlineNodeApproval deadlineNodeApproval = new DeadlineNodeApproval();
            BeanUtils.copyProperties(node,deadlineNodeApproval);
            deadlineNodeApprovalList.add(deadlineNodeApproval);
        }
        deadlineNodeApprovalMapper.batchInsertByAnnotation(deadlineNodeApprovalList);
        return "";
    }

    @Override
    public Answer<Object> groupNodeDepartmentType(JSONObject reqJson){
        String title = reqJson.getString("title");
        String state = reqJson.getString("state");
        String projectType = reqJson.getString("projectType");
        String areaName = reqJson.getString("areaName");
        String leadUnit = reqJson.getString("leadUnit");
        String label = reqJson.getString("label");
        String currentDepartment = reqJson.getString("departmentName"); //当前用户部门
        String projectChildType = reqJson.getString("projectChildType");

        String zerenDepartment = reqJson.getString("zerenDepartment");
        String nodeDepartment = reqJson.getString("nodeDepartment");
        String warnLevel = reqJson.getString("warnLevel");

        String personLiaible = reqJson.getString("personLiaible");
        String leadLeader = reqJson.getString("leadLeader");
        String projectChildCategoryType = reqJson.getString("projectChildCategoryType");
        JSONArray projectChildTypeList = reqJson.getJSONArray("projectChildTypeList");

        List<RectificationInfoApproval> recList = fetchAllRectification(currentDepartment);


        if (StrUtil.isNotBlank(projectType)){
            recList = recList.stream()
                    .filter(item -> item.getProjectType() != null &&
                            item.getProjectType().contains(projectType))
                    .collect(Collectors.toList());
        }
        if (projectChildTypeList!=null && projectChildTypeList.size()>0){
            recList = recList.stream()
                    .filter(item -> item.getProjectChildType()!=null &&
                            projectChildTypeList.contains(item.getProjectChildType()))
                    .collect(Collectors.toList());
        }
        if (StrUtil.isNotBlank(projectChildType)){
            recList = recList.stream()
                    .filter(item -> item.getProjectChildType() != null &&
                            item.getProjectChildType().equals(projectChildType))
                    .collect(Collectors.toList());
        }
        if (StrUtil.isNotBlank(projectChildCategoryType)){
            recList = recList.stream()
                    .filter(item -> item.getProjectChildCategoryType() != null &&
                            item.getProjectChildCategoryType().contains(projectChildCategoryType))
                    .collect(Collectors.toList());
        }
        if (StrUtil.isNotBlank(title)){
            recList = recList.stream()
                    .filter(item -> item.getTitle() != null &&
                            item.getTitle().contains(title))
                    .collect(Collectors.toList());
        }
        if (StrUtil.isNotBlank(leadLeader)){
            recList = recList.stream()
                    .filter(item -> item.getLeadLeader() != null &&
                            item.getLeadLeader().contains(leadLeader))
                    .collect(Collectors.toList());
        }
        if (StrUtil.isNotBlank(personLiaible)){
            recList = recList.stream()
                    .filter(item -> item.getPetitioner() != null &&
                            item.getPetitioner().contains(personLiaible))
                    .collect(Collectors.toList());
        }
        // 3. 第三步：关键修改——用 LambdaQueryWrapper 替代最后一次流过滤（核心需求）
        if (StrUtil.isNotBlank(currentDepartment)) {
            // 3.1 保留原部门名称替换逻辑
            String nodeDepartMent = currentDepartment.replace("市发改委", "发改")
                    .replace("市资建局", "资建")
                    .replace("市林业局", "林业")
                    .replace("市财政局", "财政")
                    .replace("市生态环境局", "生态")
                    .replace("市应急管理局", "应急")
                    .replace("市自然资源规划局", "自规部门")
                    .replace("市住新局", "住建");

            // 3.2 保留原关联ID获取逻辑
            List<Integer> relatedRectificationIds = getFilteredTaskIds(nodeDepartMent);
            // 3.3 保留县市区部门的额外ID逻辑
            if (COUNTY_LEVEL_DISTRICTS.contains(currentDepartment)) {
                List<Integer> departList = getFilteredAreaTaskIds(currentDepartment);
                relatedRectificationIds.addAll(departList);
            }

            // 手动构建一个Predicate，条件与LambdaQueryWrapper一致
            Predicate<RectificationInfoApproval> predicate = item ->
                    (item.getDepartmentName()!=null && item.getDepartmentName().contains(currentDepartment)) ||
                            (item.getCreatorUnit()!=null && item.getCreatorUnit().contains(currentDepartment)) ||
                            (item.getLeadUnit()!=null && item.getLeadUnit().contains(currentDepartment)) ||
                            (relatedRectificationIds != null && relatedRectificationIds.contains(item.getId()));

            recList = recList.stream().filter(predicate).collect(Collectors.toList());
        }

        List<TreeNode> newList = RectificationClassifier.classifyThreeLevels(recList,"0");
        return Answer.ok(newList);
    }

    @Override
    public Answer<Object> updateApproval(RectificationInfoApproval rectificationInfoApproval) {
        Integer id = rectificationInfoApproval.getId();
        if (id==null) {
            return Answer.error("项目id不能为空");
        }

        RectificationInfoApproval rectificationInfoApproval1 = rectificationInfoApprovalMapper.selectById(rectificationInfoApproval.getId());

        String title = rectificationInfoApproval.getTitle();
        if (StrUtil.isBlank(title)) {
            return Answer.error("项目名称不能为空");
        }

        //项目简介
        String content = rectificationInfoApproval.getContent();
        if (StrUtil.isBlank(content)) {
            return Answer.error("项目简介不能为空");
        }

        //牵头单位
        String leadUnit = rectificationInfoApproval.getLeadUnit();
        if (StrUtil.isBlank(leadUnit)) {
            return Answer.error("牵头单位不能为空");
        }

        //工作类型
        String projectType = rectificationInfoApproval.getProjectType();
        if (StrUtil.isBlank(projectType)) {
            return Answer.error("工作类型不能为空");
        }

        //牵头领导
        String leadLeader = rectificationInfoApproval.getLeadLeader();
        if (StrUtil.isBlank(leadLeader)) {
            return Answer.error("牵头领导不能为空");
        }

        //责任人
        String personLiaible = rectificationInfoApproval.getPersonLiaible();
        if (StrUtil.isBlank(personLiaible)) {
            return Answer.error("责任人不能为空");
        }

        String[] split = projectType.split("/");
        rectificationInfoApproval.setProjectType(split[0]);
        rectificationInfoApproval.setProjectChildType(split[1]);
        if (split.length>2){
            rectificationInfoApproval.setProjectChildCategoryType(split[2]);
        }

        if (rectificationInfoApproval1!=null){
            rectificationInfoApprovalMapper.updateById(rectificationInfoApproval);
        }
        return Answer.ok("修改成功");
    }

    @Override
    public Answer<Object> groupByTitle() {
        LambdaQueryWrapper<RectificationInfoApproval> rectificationInfoQueryWrapper = new LambdaQueryWrapper<>();
        rectificationInfoQueryWrapper.ne(RectificationInfoApproval::getState, "已关闭").ne(RectificationInfoApproval::getState, "已销号")
                .ne(RectificationInfoApproval::getState,"已退出").eq(RectificationInfoApproval::getApprovalState,0);
        List<RectificationInfoApproval> rectificationInfos = rectificationInfoApprovalMapper.selectList(rectificationInfoQueryWrapper);
        List<String> title = new ArrayList<>();
        for (RectificationInfoApproval rectificationInfo : rectificationInfos) {
            title.add(rectificationInfo.getTitle());
        }
        return Answer.ok(title);
    }


    private List<RectificationInfoApproval> fetchAllRectification(String currentDepartment) {
        // 1. 并行执行三个数据查询
        ExecutorService executor = Executors.newFixedThreadPool(3);

        Future<List<RectificationInfoApproval>> rectificationFuture = executor.submit(() -> {
            LambdaQueryWrapper<RectificationInfoApproval> wrapper = new LambdaQueryWrapper<>();
            wrapper.ne(RectificationInfoApproval::getState, "已关闭")
                    .ne(RectificationInfoApproval::getState, "已销号")
                    .ne(RectificationInfoApproval::getState,"已退出")
                    .eq(RectificationInfoApproval::getState,0)
                    .orderByAsc(RectificationInfoApproval::getId);
            return rectificationInfoApprovalMapper.selectList(wrapper);
        });
        // 2. 获取结果
        List<RectificationInfoApproval> rectificationList = new ArrayList<>();


        try {
            rectificationList = rectificationFuture.get();
        } catch (InterruptedException | ExecutionException e) {
            // 处理异常，记录日志等
            Thread.currentThread().interrupt();
        } finally {
            executor.shutdown();
            // 4. 合并所有列表
            List<RectificationInfoApproval> result = new ArrayList<>(rectificationList);
            return result;
        }
    }

    public List<Integer> getFilteredTaskIds(String department) {
        // 1. 先查询符合条件的任务ID（来自RectificationInfo的项目类型过滤）
        List<Long> qualifiedTaskIds = getQualifiedTaskIdsFromProjectType();
        boolean isCityLevelDepartment = !COUNTY_LEVEL_DISTRICTS.contains(department);
        if (CollectionUtils.isEmpty(qualifiedTaskIds)) {
            return new ArrayList<>();
        }
        if(!isCityLevelDepartment){
            return new ArrayList<>();
        }
        // 2. 查询这些任务ID对应的节点，并应用节点级过滤
        List<DeadlineNode> allNodes = deadlineNodeMapper.selectList(
                new LambdaQueryWrapper<DeadlineNode>()
                        .in(DeadlineNode::getRectificationId, qualifiedTaskIds)
                        .like(DeadlineNode::getDepartmentName, department)
        );

        // 3. 过滤节点（排除progress为"/"的节点）
        List<DeadlineNode> filteredNodes = allNodes.stream()
                .filter(node -> node.getProgress() == null || !"/".equals(node.getProgress()))
                .collect(Collectors.toList());
        // 定义需要保留的县市区列表（包含所有目标区域）
        // 4. 按项目类型获取对应的任务ID和允许的节点名称映射
        List<Integer> finalTaskIds = filteredNodes.stream()
                .filter(node -> {
                    // 获取该节点对应的任务信息
                    RectificationInfo rectInfo = rectificationInfoMapper.selectById(node.getRectificationId());
                    if (rectInfo == null) {
                        return false;
                    }
                    // 可选：在任务信息层面再次排除县市区（三重保险）
                    if (COUNTY_LEVEL_DISTRICTS.contains(rectInfo.getDepartmentName())) {
                        return false;
                    }
                    // 不符合任何过滤规则的节点不保留
                    return true;
                })
                // 提取任务ID并去重
                .map(DeadlineNode::getRectificationId)
                .distinct()
                .collect(Collectors.toList());

        return finalTaskIds;
    }

    private List<Long> getQualifiedTaskIdsFromProjectType() {
        LambdaQueryWrapper<RectificationInfoApproval> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(RectificationInfoApproval::getId)
                .and(w -> w
                        // 条件1：主城崛起 + 招商签约未开工重点项目
                        .or(q -> q.eq(RectificationInfoApproval::getProjectType, "高质量发展"))
                );

        return rectificationInfoApprovalMapper.selectObjs(queryWrapper).stream()
                .map(obj -> Convert.toLong(obj))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }

    private static final Set<String> COUNTY_LEVEL_DISTRICTS = new HashSet<>(Arrays.asList(
            "黄州区", "团风县", "红安县", "麻城市",
            "罗田县", "英山县", "浠水县", "蕲春县",
            "武穴市", "黄梅县"
    ));

    public List<Integer> getFilteredAreaTaskIds(String department) {
        // 1. 先查询符合条件的任务ID（来自RectificationInfo的项目类型过滤）
        List<Long> qualifiedTaskIds = getNotQualifiedTaskIdsFromProjectType();
        if (CollectionUtils.isEmpty(qualifiedTaskIds)) {
            return new ArrayList<>();
        }
        // 2. 查询这些任务ID对应的节点，并应用节点级过滤
        List<DeadlineNode> allNodes = deadlineNodeMapper.selectList(
                new LambdaQueryWrapper<DeadlineNode>()
                        .in(DeadlineNode::getRectificationId, qualifiedTaskIds)
                        .like(DeadlineNode::getDepartmentName, department)
        );

        // 3. 过滤节点（排除progress为"/"的节点）
        List<DeadlineNode> filteredNodes = allNodes.stream()
                .filter(node -> node.getProgress() == null || !"/".equals(node.getProgress()))
                .collect(Collectors.toList());
        // 定义需要保留的县市区列表（包含所有目标区域）
        // 4. 按项目类型获取对应的任务ID和允许的节点名称映射
        List<Integer> finalTaskIds = filteredNodes.stream()
                .filter(node -> {
                    // 获取该节点对应的任务信息
                    RectificationInfo rectInfo = rectificationInfoMapper.selectById(node.getRectificationId());
                    if (rectInfo == null) {
                        return false;
                    }
                    return true;
                })
                // 提取任务ID并去重
                .map(DeadlineNode::getRectificationId)
                .distinct()
                .collect(Collectors.toList());

        return finalTaskIds;
    }

    private List<Long> getNotQualifiedTaskIdsFromProjectType() {
        LambdaQueryWrapper<RectificationInfoApproval> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(RectificationInfoApproval::getId)
                .and(w -> w
                        // 条件1：主城崛起 + 招商签约未开工重点项目
                        .or(q -> q.ne(RectificationInfoApproval::getProjectType, "高质量发展"))
                );
        return rectificationInfoApprovalMapper.selectObjs(queryWrapper).stream()
                .map(obj -> Convert.toLong(obj))
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }
}
